import React, { useCallback, useEffect, useState } from 'react'
import {
  Table,
  Button,
  Space,
  Row,
  Col,
  Popconfirm,
  Modal,
  Form,
  Input,
  Select,
  InputNumber,
} from 'antd'
import { mockService } from './mock/mock-service'

const App: React.FC = () => {
  // state
  const [users, setUsers] = useState<Array<User>>([])
  const [page, setPage] = useState<number>(1)
  const [pageSize, setPageSize] = useState<number>(5)
  const [total, setTotal] = useState<number>(0)
  const [visible, setVisible] = useState<boolean>(false)

  const [form] = Form.useForm()

  /**
   * 查询用户数据
   */
  useEffect(() => {
    getUserList(page, pageSize)
  }, [])

  /**
   * 分页查询用户列表数据
   * @param page 
   * @param pageSize 
   */
  const getUserList = useCallback(async (page: number, pageSize: number) => {
    try {
      // 分页查询
      const {rows, total} = await mockService.queryPagedUserList(page, pageSize)
      setUsers(rows)
      setTotal(total)
      setPage(page)
      setPageSize(pageSize)
    } catch (error) {
      console.log(error)
    }
  }, [])

  /**
   * 删除用户操作
   */
  const removeUser = useCallback(async (id: number) => {
    try {
      // 删除
      const {status} = await mockService.deleteUser(id)
      // 删除成功，重新查询当前页数据
      if (status === 0) {
        const _page = users.length <= 1 ? page - 1 : page
        getUserList(_page, pageSize)
      }
    } catch (error) {
      console.log(error)
    }
  }, [users, page, pageSize])

  /**
   * 点击编辑按钮操作
   */
  const editUser = useCallback((user: User) => {
    // 显示编辑模态框
    setVisible(true)
    // 表单回显编辑数据
    form.setFieldsValue(user)
  }, [])

  /**
   * 确定编辑用户操作
   */
  const editConfirm = useCallback(async () => {
    try {
      const user = form.getFieldsValue()
      const {status} = await mockService.editUser(user)
      if (status === 0) {
        setVisible(false)
        form.resetFields()
        setUsers((prevUsers) => prevUsers.map(_user => _user.id === user.id ? user : _user))
      }
    } catch (error) {
      console.log(error)
    }
  }, [])

  /**
   * 取消编辑用户操作
   */
  const editCancel = useCallback(() => {
    setVisible(false)
    form.resetFields()
  }, [])

  /**
   * 列定义
   */
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '年龄',
      dataIndex: 'age',
    },
    {
      title: '性别',
      dataIndex: 'sex',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '操作',
      key: 'option',
      render(text: any, record: User) {
        return (
          <Space>
            <Button type="primary" size="small" onClick={editUser.bind(this, record)}>编辑</Button>
            <Popconfirm
              title="确定要删除当前记录吗?"
              okText="确定"
              cancelText="取消"
              onConfirm={removeUser.bind(this, record.id)}
            >
              <Button type="primary" size="small" danger>删除</Button>
            </Popconfirm>
          </Space>
        )
      },
    }
  ]

  return (
    <>
      <Row>
        <Col span={16} offset={4}>
          <Table
            columns={columns}
            dataSource={users}
            rowKey="id"
            title={() => '用户管理'}
            pagination={{
              total,
              onChange: getUserList,
              pageSize,
              current: page,
            }}
          ></Table>
        </Col>
      </Row>

      <Modal
        title="编辑用户"
        visible={visible}
        okText="确定"
        cancelText="取消"
        onOk={editConfirm}
        onCancel={editCancel}
      >
        <Form
          labelCol={{span: 6}}
          wrapperCol={{span: 12}}
          form={form}
        >
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          <Form.Item label="姓名" name="name">
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item label="年龄" name="age">
            <InputNumber placeholder="请输入年龄" />
          </Form.Item>
          <Form.Item label="性别" name="sex">
            <Select placeholder="请选择性别">
              <Select.Option value="男">男</Select.Option>
              <Select.Option value="女">女</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="邮箱" name="email">
            <Input placeholder="请输入姓名" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

export default App
